package cn.test;

import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisSentinelConnection;
import org.springframework.data.redis.connection.RedisServer;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactoryExtend;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import redis.clients.jedis.RedisContextHolder;
import redis.clients.jedis.RedisContextHolder.RedisOperationType;

/**
 * JedisSentinelPool中的监听事件，初始化连接池的时候放入的是所有的master的连接，所以导致写入的时候没有走原来的请求，这里大概需要重新封装一套出来，才能保证读写分离
 * JedisConnectionFactory中afterPropertiesSet调用初始化连接池，createPool（）
 * createPool中，调用初始化createRedisSentinelPool().
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class App extends BaseRedisDao<Object, Object> {
	@Autowired
	private JedisConnectionFactoryExtend con;

	@Test
	public void testRedis() {
		for (int i = 0;; i++) {
			try {
//				RedisContextHolder.set(RedisOperationType.WRITE);
//				valueOperations.set("asd", "1");
//				System.out.println(valueOperations.get("asd"));
				RedisContextHolder.set(RedisOperationType.READ);
				System.out.println(valueOperations.get("asd"));
				valueOperations.set("asd", "2");
				System.out.println(valueOperations.get("asd"));
				if (i % 1000 == 0) {
					System.out.println(con.getConnection());
					System.out.println(i);
				}
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 输出所有的节点信息
	 */
	@Test
	public void listNode() {
		RedisSentinelConnection conn = getRedisTemplate().getConnectionFactory().getSentinelConnection();
		for (RedisServer m : conn.masters()) {
			System.out.println("master => " + m);// 打印master信息
			Collection<RedisServer> slaves = conn.slaves(m);
			// 打印该master下的所有slave信息
			for (RedisServer s : slaves) {
				
			}
			System.out.println("--------------");
		}
	}
}
